<?php

/**
 * @Author: king
 * @Date:   2019-05-05 20:14:51
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-04 23:48:14
 */
namespace App\Http\Controllers\Api\v3;

use App\Http\Controllers\Api\BaseController;
use App\Tools\Validates\CommunityValidate;
use App\Tools\Validates\CommunityComment;
use Illuminate\Http\Request;
use App\Models\Api\Community;
use App\Models\Api\Comment;
use App\Models\Api\MessageCenter;
use App\Tools\Base\Avatar;
use App\Models\Api\User;
use App\Tools\Push;
use Illuminate\Pagination\Paginator;

use DB;

class CommunityController extends BaseController
{
    //首页数据
    public function index(Request $request){

       if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('content')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $page= $param['page'] ?? '0';
        $group_id =$param['group_id'] ??'1';
       // $type = $param['type'] ??'1';
        $list=(new Community())->getContentData(['uid'=>$request->uid,'page'=>$page,'group_id'=>$group_id]);
        if($list['list']){
            return show(config('code.success'), '加载成功', $list);
        }else{
            return show(config('code.success'), '没有更多数据',$list);
            //return self::showData(210,'没有更多数据',$list,10004);
        }
    }
    //说说点赞
    public function sendGood(Request $request){
      if (!$request->isMethod('POST')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->sendGood(['uid'=>$request->uid,'id'=>$id]);
        if($res =='1'){
            return show(config('code.success'), '点赞成功', $res);
        }else{
            return show(config('code.success'), '取消赞成功', $res);
        }
    }

    //收藏
    public function sendCollection(Request $request){
        if (!$request->isMethod('POST')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->sendCollection(['uid'=>$request->uid,'id'=>$id]);
        if($res =='1'){
            return show(config('code.success'), '收藏成功', $res);
        }else{
            return show(config('code.success'), '取消收藏成功', $res);
        }
    }
    //举报
    public function sendReport(Request $request){
        if (!$request->isMethod('POST')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->sendReport(['uid'=>$request->uid,'id'=>$id]);
        if($res) return show(config('code.success'),'举报成功');
         return show(config('code.error'),'你已经举报了');
    }

    //关注
    public function sendFollow(Request $request){
      if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->sendFollow(['uid'=>$request->uid,'id'=>$id]);
        if($res){
            return show(config('code.success'),'关注成功');
        }else{
            return show(config('code.success'),'取消成功');
        }
    }
    //发送动态
    public function sendContent(Request $request){
      if (!$request->isMethod('post')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('community')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
       $result =contentCensor($param['communityContent']);
       if ($result['status'] === 2) {
           // \Log::info('占卜错误:' . $validate->getError());
            return show(config('code.error'), $result['msg']);
        }
        $data = [
            'uid'=>$request->uid,
            'content'=>$param['communityContent'],
            'images'=>$param['images'] ?? '',
            'video'=>$param['video'] ?? '',
            'group_id'=>$param['group_id'],
            'address'=>$param['address'],
            'location'=>$param['location'],
            'isTop'=>$param['isTop'] ?? '0',
            'type'=>$param['type'] ?? '1',
            ];
        $res=(new Community())->sendContent($data);
        return show(config('code.success'),'发布成功',$res);
    }
    //获取动态的类别
    public function  getCommunityType(Request $request){
         if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $res=(new Community())->getCommunityType(['uid'=>$request->uid]);
        return show(config('code.success'),'获取成功',$res);
    }
    //获取动态的详情
    public function  getCommunityInfo(Request $request){
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->getCommunityInfo(['uid'=>$request->uid,'id'=>$id]);
       return show(config('code.success'),'获取成功',$res);
    }
    //获取我的关注
    public function getMyFollow(Request $request){
         if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('content')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $page= $param['page'] ??'1';
        $res=(new Community())->getMyFollow(['uid'=>$request->uid,'page'=>$page]);
        return show(config('code.success'),'获取成功',$res);
    }
    //获取最热
    public function getCommunityFire(Request $request){
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('content')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $page= $param['page'] ??'1';
        $list=(new Community())->getCommunityFire(['uid'=>$request->uid,'page'=>$page]);
        if($list['list']){
            return show(config('code.success'),'获取成功',$list);
        }else{
            return show(config('code.success'),'没有更多数据',$list);
        }
    }
    //删除说说
    public function removeCommunity(Request $request){
    if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        (new Community())->removeCommunity(['uid'=>$request->uid,'id'=>$id]);
        return show(config('code.success'),'删除成功');
    }
    //获取我的发布
    public function getUserCommunity(Request $request){
       if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
           }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $page =$param['page'] ??'1';
        $res=(new Community())->getUserCommunity(['uid'=>$request->uid,'id'=>$id,'page'=>$page]);
        return show(config('code.success'),'获取成功',$res);

    }
    //获取用户的点赞 评论 粉丝等信息
    public function getUserCommunityIndex(Request $request){
       if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->getUserCommunityIndex(['uid'=>$request->uid,'token'=>$this->user['token'],'id'=>$id]);
         return show(config('code.success'),'获取成功',$res);
    }
    //获取我的收藏
    public function myCollection(Request $request){
      if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
          }
        $param  = $request->all();
        $page =$param['page'] ??'1';
        $res=(new Community())->myCollection(['uid'=>$request->uid,'page'=>$page]);
       return show(config('code.success'),'获取成功',$res);
    }
     //获取我的收藏
    public function myGood(Request $request){
      if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
          }
        $param  = $request->all();
        $page =$param['page'] ??'1';
        $res=(new Community())->myGood(['uid'=>$request->uid,'page'=>$page]);
       return show(config('code.success'),'获取成功',$res);
    }
    //新增访问
    public function addVisitorNumber(Request $request){
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
      }
        $res=(new Community())->addVisitorNumber(['uid'=>$request->uid]);
        return show(config('code.success'),'获取成功',$res);
    }
    //获取置顶
    public function getCommunityTop(Request $request){
     if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
         }
        $res=(new Community())->getCommunityTop(['uid'=>$request->uid]);
        return show(config('code.success'),'获取成功',$res);
    }
    //取消置顶
    public function closeTop(Request $request){
          if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
          }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('id')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $id= $param['id'];
        $res=(new Community())->closeTop(['uid'=>$request->uid,'id'=>$id]);
        return show(config('code.success'),'取消成功',$res);
    }
    //搜索动态
    public function searchAll(Request $request){
      if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
          }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('search')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $searchValue= $param['searchValue'];
        $page= $param['page'] ??'1';
        $res=(new Community())->searchAll(['uid'=>$request->uid,'searchValue'=>$searchValue,'page'=>$page]);
       return show(config('code.success'),'获取成功',$res);
    }
    //获取热门搜索
    public function getHotSearch(Request $request){
        if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
          }
       $res=(new Community())->getHotSearch();
       return show(config('code.success'),'获取成功',$res);
    }

     //首页数据
    public function video(Request $request){
      if (!$request->isMethod('get')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param  = $request->all();
        $validate = new CommunityValidate();
        if ($validate->scene('content')->check($param) !== true) {
            return show(config('code.error'), $validate->getError());
        }
        $page = $param['page'] ?? '0';
        $group_id = $param['group_id'] ?? '1';
        $type = $param['type'] ?? '2';
        $id = $param['id'] ?? '0';
        $list=(new Community())->getVideoData(['uid'=>$request->uid,'page'=>$page,'group_id'=>$group_id,'type'=>$type,'id'=>$id]);
        if($list['list']){
            return show(config('code.success'), '加载成功', $list);
        }else{
            return show(config('code.error'), '没有更多视频',$list);
            //return self::showData(210,'没有更多数据',$list,10004);
        }
    }
    /**
     * 上传文件图片及视频
     */
    public function upload($dir = 'upload')
    {
        $avatar = new Avatar();
        return $avatar->upload($dir);
    }

      /*
     * 圈子评论拉取
     */
    public function getComment(Request $request)
    {

        $id = $request->input('id');
        if (empty($id)) {
            return show(config('code.error'), '圈子id不能为空', [], 403);
        }
        $list = Community::with(['user' => function ($query) {
            $query->select('id', 'nickname', 'avatar');
        }])
            ->OrderBy('create_time', 'desc')
            ->findOrFail($id);
        // 检查圈子是否为空
         if (!$list) {
           return show(config('code.error'), '圈子不存在', [], 404);
        }
        $data = $list->comments('p')->with([
            'user' => function ($query) {
                   $query->select('user.id','user.uen','user.tel','user.uc_id','user.nickname','user.sex','user.avatar','user.status','user.has_self_recode','user.forbidden','user.regid', 'recode_astro.sun', 'recode_astro.moon','recode_astro.asc') // 数据字段
                    ->join('recode', 'user.id', '=', 'recode.uid')
                    ->join('recode_astro', 'recode.id', '=', 'recode_astro.rid')
                    ->where('recode.isself','1'); //判断档案ID为1自己的信息
                },
            'childs' => function ($query) {
                $query->with('user','rUser'); //输出 child comments信息
            }
        ])->withCount('childs')->paginate(15);
     if ($data->isEmpty()) {
         return show(config('code.success'), '没有更多评论数据',$data);
    }
   // 处理点赞信息
    if ($request->uid) {
        foreach ($data as &$comment) {
           // var_dump($comment);die;
            $comment['is_liked'] = $comment->isLike(true, $request->uid);
            foreach ($comment['childs'] as &$childComment) {
                $childComment['is_liked'] = $childComment->isLike(true, $request->uid);
            }
        }
    }
        $commentlist =  $data->toArray();
        $totalChildCount = 0; // Initialize the total child count
        foreach ($commentlist['data'] as $comment) {
            $totalChildCount += $comment['childs_count'];
        }

        $commentlist['total'] = $commentlist['total'] + $totalChildCount;
        return show(200, '评论拉取成功', $commentlist);
    }

 // 增加评论 api
    public function sendComment(Request $request)
    {
        $community_id = $request->input('id'); //文章id
        $user_id    = $request->uid; //评论id
        $content    = $request->input('content'); //回复内容
        $p_id       = $request->input('pid', 0); // 回复楼层id
        $r_id       = intval($request->input('rid', 0)); //回复用户id

         $comment = DB::table('comment')
             ->where(['community_id' => $community_id, 'uid' => $request->uid, 'content' => $content])->first();

         if (!empty($comment)) {
             return show(0, '不要重复评论', []);
         }
       $result =contentCensor($content);
       if ($result['status'] === 2) {
           // \Log::info('占卜错误:' . $validate->getError());
            return show(config('code.error'), $result['msg']);
        }
        $data = [
            'community_id' => $community_id,
            'uid'    => $user_id,
            'content'    => $content,
            'p_id'       => $p_id,
            'to_uid'       => $r_id,
        ];

        // \Log::info('拦截：' . $data);
        $validate = new \App\Tools\Validates\CommunityComment();

        if (!$validate->scene('add')->check($data)) {
            return show(config('code.error'), (string) $validate->getError());
        }

        $comment    = (new User())->Commity_comments()->create($data);
        $Community = Community::find($comment['community_id']);
        $Community->increment('count_comment', 1);
        $comment->increment('count_comment', 1);
        $comment = $comment->where(['id'=>$comment['id'],'community_id'=>$comment['community_id'],'uid'=>$request->uid])->with('user','rUser')->first();
        if($comment['to_uid'] !=0 && $comment['to_uid'] !=NULL){
            $messageData = [
                    'uid' => $comment['to_uid'],
                    'r_uid'=>$comment['uid'],
                    'type' => 3,
                    'cid' => 4, //圈子分类cid
                    'title' => '你在圈子评论有回复',
                    'content' => $comment['content'],
                    'link' =>'getCommunityInfo?id='.$community_id,
                    'target' => "local",
                ];
            //添加消息
         (new MessageCenter())->pushMessage($messageData);
         (new Push())->pushSpecial($comment['rUser']['regid'], '你在圈子评论有回复,点击查看详情！', [
                        'action' => 'getCommunityInfo',
                        'id' => $community_id,
                    ]);
        }
         \Log::info('推送成功：' . $comment);

        if ($comment) {
            return show(config('code.success'), 'Reply success.', $comment);
        } else {
            return show(config('code.error'), '回复失败,请稍后再试');
        }

    }
     // 回复我的评论
    public function reply_me(Request $request)
    {
        $page     = intval($request->input('page', 10));
        $user     = User::select('id', 'nickname', 'avatar')->where('id', $request->uid)->first();
        $Comments = $user->Commity_rMyComments('p')->with('user','rUser','childs','childs.user', 'childs.rUser')->paginate(10)->toArray();

        return show(200, '回复我的评论', $Comments);
    }
     // 删除评论 api
    public function destroy(Request $request, Comment $comment)
    {
        if (!$request->isMethod('post')) {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id   = $request->input('id');
        $community_id   = $request->input('c_id');
        $Community = Community::where(['id'=>$community_id])->first();
        $Community->decrement('count_comment', 1);
        $data = $comment->destroy($id);
        if ($data) {
            return show(config('code.success'), '删除成功', $data);
        } else {
            return show(config('code.error'), '删除失败');
        }
    }

     // 点赞评论
    public function sendCommentGood(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return show(config('code.error'), '评论id不能为空', [], 403);
        }
        $comment = Comment::findOrFail($id);
        $res     = $comment->isLike(true, $request->uid);
        if ($res == 1) {
            $like = $comment->likes()->where(['uid' => $request->uid])->delete();
            $comment->decrement('count_like', 1);
            $img       = 'images/111_03.jpg';
            $zanstatus = '-1';
            $message   = 'Good cancel success.';
        } else {
            $comment->likes()->create(['uid' => $request->uid]);
            $comment->increment('count_like', 1);
            $img       = 'images/111_03-on.jpg';
            $zanstatus = '1';
            $message   = 'Good success.';
        }

        $data = ['count' => $comment->count_like, 'img' => $img, 'status' => $zanstatus];
        return show(200, $message, $data);
    }

   /**
     * 过滤敏感词汇
     * @param $content
     * @return bool
     */
    protected function filter_words($content)
    {
        $words  = config('words.words');
        $status = false;
        foreach ($words as $w) {
            if (strpos($content, $w) !== false) {
                $status = true;
            }
        }

        if (in_array($content, $words)) {
            $status = true;
        }

        return $status;
    }
}
